package messageMeTransfer.utilities;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Stack;

import messageMeTransfer.interfaces.IListener;
import messageMeTransfer.interfaces.IPackage;

public class Client implements IListener {

	private Socket socket = null;

	private ObjectInputStream objectInputStream = null;
	private ObjectOutputStream objectOutputStream = null;

	public Stack<IPackage> recievedPackages = null;

	public Client(Socket clientSocket) {
		this.socket = clientSocket;
		this.initializeIO();

		this.recievedPackages = new Stack<IPackage>();
	}

	public void sendPackage(IPackage packageToSend) {
		try {
			this.objectOutputStream.writeObject(packageToSend);
			this.objectOutputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void packageRecieved(IPackage iPackage) {
		this.recievedPackages.push(iPackage);
	}
	
	private void initializeIO() {
		try {
			this.objectOutputStream = new ObjectOutputStream(
					this.socket.getOutputStream());
			objectOutputStream.flush();

			this.objectInputStream = new ObjectInputStream(
					this.socket.getInputStream());

			PackageReciever reciever = new PackageReciever(
					this.objectInputStream);
			reciever.addListener(this);
			reciever.start();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void closeConnection() {
		try {
			this.objectInputStream.close();
			this.objectOutputStream.close();
			this.socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
